// 初始化所有图表
let charts = {
    customerDistribution: null,
    loginHeatmap: null,
    productHoldings: null,
    marketingTrend: null,
    assetGrowth: null
};

// 更新时间显示
function updateDateTime() {
    const now = new Date();
    document.getElementById('updateTime').textContent = now.toLocaleString();
}

// 初始化图表
function initCharts() {
    charts.customerDistribution = echarts.init(document.getElementById('customerDistribution'));
    charts.loginHeatmap = echarts.init(document.getElementById('loginHeatmap'));
    charts.productHoldings = echarts.init(document.getElementById('productHoldings'));
    charts.marketingTrend = echarts.init(document.getElementById('marketingTrend'));
    charts.assetGrowth = echarts.init(document.getElementById('assetGrowth'));
}

// 加载概览数据
function loadOverview() {
    $.get('/api/overview', function(data) {
        $('#totalCustomers .number').text(data.total_customers.toLocaleString());
        $('#totalAssets .number').text('¥' + (data.total_assets / 100000000).toFixed(2) + '亿');
        $('#activeUsers .number').text(data.active_users.toLocaleString());
        $('#marketingResponse .number').text(data.marketing_response_rate.toFixed(2) + '%');
    });
}

// 更新客户分布图表
function updateCustomerDistribution() {
    $.get('/api/customer_distribution', function(data) {
        const option = {
            title: {
                text: '客户年龄分布',
                textStyle: { color: '#fff' }
            },
            tooltip: { trigger: 'item' },
            legend: {
                top: '5%',
                left: 'center',
                textStyle: { color: '#fff' }
            },
            series: [{
                name: '年龄分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: { show: false },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                data: Object.entries(data.age_distribution).map(([name, value]) => ({
                    name,
                    value
                }))
            }]
        };
        charts.customerDistribution.setOption(option);
    });
}

// 更新登录持续时间分布表格
function updateLoginHeatmap() {
    $.get('/api/login_duration', function(data) {
        const option = {
            title: {
                text: '客户登录持续时间分布',
                textStyle: { color: '#fff' }
            },
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    return `${data.periods[params.value[0]]} - ${data.durations[params.value[1]]}<br/>登录人数: ${params.value[2].toLocaleString()}`;
                }
            },
            legend: {
                show: false
            },
            grid: {
                top: '5%',
                bottom: '15%',
                left: '15%',
                right: '5%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.periods,
                axisLabel: {
                    color: '#fff',
                    interval: 0,
                    rotate: 0,
                    fontSize: 12,
                    margin: 15
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                }
            },
            yAxis: {
                type: 'category',
                data: data.durations,  // 使用原始顺序，因为后端已经正确排序
                axisLabel: {
                    color: '#fff',
                    fontSize: 12,
                    margin: 20,
                    width: 80,
                    overflow: 'break',
                    lineHeight: 14
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                }
            },
            visualMap: {
                min: 0,
                max: Math.max(...data.data.flat()),
                calculable: true,
                orient: 'horizontal',
                left: 'center',
                bottom: '0%',
                textStyle: { color: '#fff' },
                inRange: {
                    color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',
                           '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
                }
            },
            series: [{
                name: '登录人数',
                type: 'heatmap',
                data: data.data.map((row, i) => 
                    row.map((val, j) => [i, j, val])  // 使用原始索引，因为后端已经正确排序
                ).flat(),
                label: {
                    show: true,
                    color: '#fff',
                    formatter: function(params) {
                        return params.value[2] > 0 ? params.value[2].toLocaleString() : '';
                    }
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        charts.loginHeatmap.setOption(option);
    });
}

// 更新产品持有情况
function updateProductHoldings() {
    $.get('/api/product_holdings', function(data) {
        const option = {
            title: {
                text: '产品持有情况分析',
                textStyle: { color: '#fff' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    const productData = data.product_details[params[0].dataIndex];
                    return `${productData.product}<br/>
                           持有人数: ${productData.holders.toLocaleString()}<br/>
                           渗透率: ${productData.penetration}%<br/>
                           平均余额: ¥${(productData.avg_balance/10000).toFixed(2)}万`;
                }
            },
            legend: {
                data: ['持有人数', '渗透率', '平均余额'],
                textStyle: { color: '#fff' },
                top: '5%'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.product_details.map(item => item.product),
                axisLabel: { 
                    color: '#fff',
                    interval: 0
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '持有人数',
                    position: 'left',
                    axisLabel: {
                        color: '#fff',
                        formatter: value => (value/10000).toFixed(1) + '万'
                    }
                },
                {
                    type: 'value',
                    name: '渗透率',
                    position: 'right',
                    offset: 80,
                    max: 100,
                    axisLabel: {
                        color: '#fff',
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: '平均余额',
                    position: 'right',
                    axisLabel: {
                        color: '#fff',
                        formatter: value => (value/10000).toFixed(0) + '万'
                    }
                }
            ],
            series: [
                {
                    name: '持有人数',
                    type: 'bar',
                    barWidth: '30%',
                    data: data.product_details.map(item => item.holders),
                    itemStyle: {
                        color: '#4992ff'
                    }
                },
                {
                    name: '渗透率',
                    type: 'line',
                    yAxisIndex: 1,
                    data: data.product_details.map(item => item.penetration),
                    itemStyle: {
                        color: '#fac858'
                    },
                    symbol: 'circle',
                    symbolSize: 8,
                    lineStyle: {
                        width: 3
                    }
                },
                {
                    name: '平均余额',
                    type: 'line',
                    yAxisIndex: 2,
                    data: data.product_details.map(item => item.avg_balance),
                    itemStyle: {
                        color: '#91cc75'
                    },
                    symbol: 'diamond',
                    symbolSize: 8,
                    lineStyle: {
                        width: 3,
                        type: 'dashed'
                    }
                }
            ]
        };
        
        // 添加产品组合分布的玫瑰图
        const roseOption = {
            series: [{
                type: 'pie',
                roseType: 'area',
                radius: ['20%', '70%'],
                center: ['50%', '50%'],
                data: data.combination_stats.labels.map((label, index) => ({
                    name: label,
                    value: data.combination_stats.values[index]
                })),
                label: {
                    color: '#fff'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                }
            }]
        };
        
        // 合并两个图表的配置
        const finalOption = {
            ...option,
            grid: [{
                left: '5%',
                right: '50%',  // 增加右侧间距
                bottom: '15%',  // 增加底部间距
                top: '15%'
            }],
            series: [
                // 柱状图和折线图系列
                {
                    name: '持有人数',
                    type: 'bar',
                    barWidth: '30%',
                    data: data.product_details.map(item => item.holders),
                    itemStyle: {
                        color: '#4992ff'
                    }
                },
                {
                    name: '渗透率',
                    type: 'line',
                    yAxisIndex: 1,
                    data: data.product_details.map(item => item.penetration),
                    itemStyle: {
                        color: '#fac858'
                    },
                    symbol: 'circle',
                    symbolSize: 8,
                    lineStyle: {
                        width: 3
                    }
                },
                {
                    name: '平均余额',
                    type: 'line',
                    yAxisIndex: 2,
                    data: data.product_details.map(item => item.avg_balance),
                    itemStyle: {
                        color: '#91cc75'
                    },
                    symbol: 'diamond',
                    symbolSize: 8,
                    lineStyle: {
                        width: 3,
                        type: 'dashed'
                    }
                },
                // 玫瑰图系列
                {
                    type: 'pie',
                    roseType: 'area',
                    radius: ['15%', '35%'],  // 减小玫瑰图大小
                    center: ['75%', '50%'],  // 调整玫瑰图位置
                    data: data.combination_stats.labels.map((label, index) => ({
                        name: label,
                        value: data.combination_stats.values[index]
                    })),
                    label: {
                        color: '#fff',
                        formatter: '{b}: {d}%'  // 显示百分比
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold'
                        }
                    },
                    itemStyle: {
                        borderRadius: 4
                    }
                }
            ]
        };
        
        charts.productHoldings.setOption(finalOption);
    });
}

// 更新营销效果漏斗图
function updateMarketingTrend() {
    $.get('/api/marketing_funnel', function(data) {
        const option = {
            title: {
                text: '营销转化漏斗分析',
                textStyle: { color: '#fff' }
            },
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    const funnelData = data.funnel.find(d => d.name === params.name);
                    return `${params.name}<br/>
                           数量: ${params.value.toLocaleString()}<br/>
                           转化率: ${funnelData.rate}%`;
                }
            },
            legend: {
                data: data.funnel.map(item => item.name),
                textStyle: { color: '#fff' },
                top: '5%'
            },
            series: [
                {
                    name: '营销漏斗',
                    type: 'funnel',
                    left: '10%',
                    right: '10%',
                    top: '15%',
                    bottom: '10%',
                    width: '80%',
                    min: 0,
                    max: data.funnel[0].value,
                    minSize: '0%',
                    maxSize: '100%',
                    sort: 'descending',
                    gap: 2,
                    label: {
                        show: true,
                        position: 'inside',
                        formatter: function(params) {
                            const funnelData = data.funnel.find(d => d.name === params.name);
                            return `${params.name}\n转化率: ${funnelData.rate}%`;
                        },
                        fontSize: 14,
                        color: '#fff'
                    },
                    labelLine: {
                        length: 10,
                        lineStyle: {
                            width: 1,
                            type: 'solid'
                        }
                    },
                    itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 1
                    },
                    emphasis: {
                        label: {
                            fontSize: 16,
                            color: '#fff'
                        }
                    },
                    data: data.funnel.map(item => ({
                        value: item.value,
                        name: item.name
                    }))
                }
            ],
            color: ['#91cc75', '#fac858', '#5470c6', '#73c0de', '#ee6666']
        };
        charts.marketingTrend.setOption(option);
    });
}

// 更新资产提升趋势
function updateAssetGrowth() {
    $.get('/api/asset_growth', function(data) {
        const option = {
            title: {
                text: '客户资产提升趋势',
                textStyle: { color: '#fff' }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    let result = params[0].name + '<br/>';
                    params.forEach(param => {
                        result += param.seriesName + ': ' + 
                            (param.seriesType === 'line' ? param.value + '%' : '¥' + param.value) + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['资产增长率', ...Object.keys(data.asset_level_trends)],
                textStyle: { color: '#fff' },
                top: '5%'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.months,
                axisLabel: { color: '#fff' }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '增长率',
                    axisLabel: {
                        color: '#fff',
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: '平均资产',
                    axisLabel: {
                        color: '#fff',
                        formatter: '¥{value}'
                    }
                }
            ],
            series: [
                {
                    name: '资产增长率',
                    type: 'line',
                    data: data.growth_rates.map(item => item.growth_rate),
                    smooth: true,
                    yAxisIndex: 0
                },
                ...Object.entries(data.asset_level_trends).map(([level, values]) => ({
                    name: level,
                    type: 'bar',
                    stack: 'asset_level',
                    data: values,
                    yAxisIndex: 1
                }))
            ]
        };
        charts.assetGrowth.setOption(option);
    });
}

// 窗口大小改变时重置图表大小
function resizeCharts() {
    Object.values(charts).forEach(chart => {
        if (chart) {
            chart.resize();
        }
    });
}

// 初始化函数
function init() {
    updateDateTime();
    initCharts();
    loadOverview();
    updateCustomerDistribution();
    updateLoginHeatmap();
    updateProductHoldings();
    updateMarketingTrend();
    updateAssetGrowth();

    // 设置定时刷新
    setInterval(updateDateTime, 1000);
    setInterval(() => {
        loadOverview();
        updateCustomerDistribution();
        updateLoginHeatmap();
        updateProductHoldings();
        updateMarketingTrend();
        updateAssetGrowth();
    }, 5 * 60 * 1000); // 每5分钟刷新一次数据

    // 监听窗口大小改变
    window.addEventListener('resize', resizeCharts);
}

// 页面加载完成后初始化
$(document).ready(init);
